<?php

declare(strict_types=1);

/**
 * @Author:     Frank
 * @contact     frank_hhm@163.com
 * @Date:       2023-01-30 11:06:49
 * @Last Modified time: 2023-02-13 16:40:54
 */
namespace app\common\services\user;

use app\common\dao\user\UserDao;
use app\common\services\user\UserService;

use frank\base\BaseService;
use frank\exception\CommonException;
use frank\exception\AuthException;
use frank\utils\helper\ArrayHelper;
use frank\services\CacheService;
use frank\services\JwtAuthService;

use think\facade\Env;

/**
 * Class UserAuthService
 */
class UserAuthService extends BaseService
{

    /**
     * UserAuthService constructor.
     * @param UserDao $dao
     */
    public function __construct(UserDao $dao)
    {
        $this->dao = $dao;
    }

     /**
     * 获取授权信息
     */
    public function parseToken($token): array
    {
        $md5Token = is_null($token) ? '' : Env::get('redis.jwt').md5($token);
        if ($token === 'undefined') {
            throw new AuthException('请登录', 410000);
        }
        if (!$token || !$tokenData = CacheService::instance()->getTokenBucket($md5Token))
            throw new AuthException('请登录', 410000);

        if (!is_array($tokenData) || empty($tokenData) || !isset($tokenData['uid'])) {
            throw new AuthException('请登录', 410000);
        }

        //设置解析token
        [$id, $type] = JwtAuthService::instance()->parseToken($token);

        try {
            JwtAuthService::instance()->verifyToken();
        } catch (\Throwable $e) {
            if (!request()->isCli()) CacheService::instance()->clearToken($md5Token);
            throw new AuthException('登录已过期,请重新登录', 410000);
        }
        $user = UserService::instance()->getDetail([
            'id'=>$id, 'status' => 1
        ]);
        if (!$user || $user['id'] != $tokenData['uid']) {
            if (!request()->isCli()) CacheService::instance()->clearToken($md5Token);
            throw new AuthException('登录状态有误,请重新登录', 410000);
        }
        $tokenData['type'] = $type;
        return compact('user', 'tokenData');
    }

}